package jp.eisbahn.mgapi.http;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletResponse;

/**
 * This utility class has some convenience methods.
 * @author Yoichiro Tanaka
 */
public final class HttpUtils {

    /**
     * Initialize this instance.
     */
    private HttpUtils() {
    }

    /**
     * Retrieve whether the request is successful or not.
     * @param response The response object.
     * @return If succeed, return true.
     */
    public static boolean isSuccess(final HttpResponse response) {
        int responseCode = response.getResponseCode();
        return responseCode == HttpServletResponse.SC_OK
            || responseCode == HttpServletResponse.SC_CREATED;
    }

    /**
     * Build the query parameter string.
     * @param parameterMap The map object which has each parameter values.
     * @return The query parameter string.
     */
    public static String createQueryParameterString(
            final Map<String, String> parameterMap) {
        try {
            StringBuilder sb = new StringBuilder();
            boolean first = true;
            for (Entry<String, String> entry : parameterMap.entrySet()) {
                if (first) {
                    first = false;
                } else {
                    sb.append("&");
                }
                sb.append(entry.getKey());
                sb.append("=");
                sb.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
            }
            return sb.toString();
        } catch (UnsupportedEncodingException e) {
            throw new IllegalStateException(e);
        }
    }

    /**
     * Build the query parameter string.
     * @param parameters Pairs with a key and value.
     * @return The query parameter string.
     */
    public static String createQueryParameterString(
            final String[]... parameters) {
        try {
            StringBuilder sb = new StringBuilder();
            boolean first = true;
            for (int i = 0; i < parameters.length; i++) {
                String[] param = parameters[i];
                if (param != null) {
                    if (first) {
                        first = false;
                    } else {
                        sb.append("&");
                    }
                    sb.append(param[0]);
                    sb.append("=");
                    sb.append(URLEncoder.encode(param[1], "UTF-8"));
                }
            }
            return sb.toString();
        } catch (UnsupportedEncodingException e) {
            throw new IllegalStateException(e);
        }
    }

}
